<?php
/**
 * 支付参数获取类
 * @author chat
 * @version 1.0
 */

namespace app\common\library;


use Config;
use Env;

class Payment
{

    public static $wxpay = [
        'appid'=>'wx644d605bba2722dc',
        'mchid'=>'1525898021',
        'apikey'=>'yjzh365mj19870727yjzh365mj870727'
    ];

    public static $alipay = [
        'appid' => '2019091467365984',
        
        'rsaPrivateKey' => 'MIIEowIBAAKCAQEAw5f86w+F1bfQMaw3Wz17lq7cgTz+BjxNSBT0gDNzJPAAVMPe2n85sYM5iFKnhfgWrHDJeX3yTEFzJsjb1wZmKUYwVyvJhSQy4ivQKF8RTBrsl6fOhJTL4z7hrEwjd6EbqrpfzbJpU2J7qQWWNgUhGsJ1Q8idMimMy7t+p3HsclFBPpSvbDO4vO+5qDE7Xq4k3wDlTAT8wT4R4Wcm3IDnF37sABZiJlNzSymq+Lg9fhs/qTKf9RcjrGGjqQC6gj49kc02KIlXW3OwqSMi2k1QZpsn2u+UhPCesy5I7AvACVSxws8BmPQVQm3ZNzg2GOA3LyDIzsC71buFdubMW/QBiQIDAQABAoIBAHGEgJGcTLyhFf/+R5J4uIXXrrqDP5s23FN9dfoB4k4JzOdlVq3RMRbJZlasQfYK6n3iZ8xPQJTpV3+nC5BccmZ6CgxNqYPQYofJjeIgatWUusO57K4d/cdB85AgEGWZ54jK6ldjuKVgfwy15Vws1e3F9nEEudcnLkP/6Z4dDHG7mk5QmjQHL2vam2crv9jcrwFF7euCdQ8WdTeCJcdu8JB2U6+bJj58r809zfpZKT4bpFQk1/6TAyCGKwlQ/xQLTQHAzCQe2jOYioVBr441Icsi7lM0ydCKVCXlU6kQv3yQxsXyiXssd4pV/tD639Znn1sNX0BClQ5XWqmJi5ibcgECgYEA81hG23AN56T6gR1HO3VdU7Da7yk44UT3fKGVESEv6KcPg8H9gCYhAYCKTf63R0i2vJJWNaw80MeQ2vsF4aK7Av8GBItb6JqRidmztPgWfBponA+84ue1MQVMkXNsMHZrmtNh61dEz4kZ4f8dROqusNOxudo3PIo5+b1JQM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xDRBxkXxzsTnoFKc84wQfobG212EKSey/CdyVfPv4dTVnoIZxQlnEkwIDAQAB',
        'gatewayUrl' => 'https://openapi.alipay.com/gateway.do',
        'notify_url' => '',     // 你也可以在下单时单独设置来想覆盖它
    ];

    /**
     * @param $params
     * @return array
     * @throws \Exception
     * 调用统一下单方法返回支付参数
     */
    public static function getWxAppPay($params)
    {
        $package = array();
        $package['appid'] = self::$wxpay['appid'];
        $package['mch_id'] = self::$wxpay['mchid'];
        //$package['sub_mch_id'] = $wechat['sub_mch_id'];
        $package['nonce_str'] = self::random(8);
        $package['body'] = $params['title'];
        $package['out_trade_no'] = $params['tid'];
        $package['total_fee'] = $params['fee'];
        $package['spbill_create_ip'] = $params['ip'];
        $package['attach'] = !empty($params['type']) ? $params['type'] : "";
        $package['time_start'] = date('YmdHis', time());
        $package['time_expire'] = date('YmdHis', time() + 3600);
        $package['notify_url'] = $params['notify_url'];
        // var_dump($package['notify_url']);
        $package['trade_type'] = 'APP';
//        $package['trade_type'] = 'APP';
        ksort($package, SORT_STRING);
        $string1 = '';
        foreach ($package as $key => $v) {
            if (empty($v)) {
                continue;
            }
            $string1 .= $key . '=' . $v . '&';
        }
        $string1 .= 'key=' . self::$wxpay['apikey'];
//		var_dump($string1);
        $package['sign'] = strtoupper(md5($string1));

        $dat = self::array2xml($package);
        $response = self::curl('https://api.mch.weixin.qq.com/pay/unifiedorder', $dat, 1);
//        if ($this->is_error($response))
//        {
//            return $response;
//        }
        $xml = simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA);
        if (strval($xml->return_code) == 'FAIL') {
            return exception(strval($xml->return_msg));
        }
        if (strval($xml->result_code) == 'FAIL') {
            return exception(strval($xml->err_code) . ': ' . strval($xml->err_code_des));
        }
        libxml_disable_entity_loader(true);
        $result = json_decode(json_encode($xml), true);
        $noncestr = (array)$xml->nonce_str;
        $prepayid = (array)$xml->prepay_id;
        $partnerid = (array)$xml->mch_id;
        $sign = (array)$xml->sign;
        $wOpt = array('appid' => self::$wxpay['appid'], 'partnerid' => $partnerid[0], 'prepayid' => $prepayid[0], 'package' => 'Sign=WXPay', 'noncestr' => self::random(8), 'timestamp' => (string)time());
        ksort($wOpt, SORT_STRING);
        $string = '';
        foreach ($wOpt as $key => $v) {
            if (empty($v)) {
                continue;
            }
            $string .= $key . '=' . $v . '&';
        }
        // var_dump($string);
        $string .= 'key=' . self::$wxpay['apikey'];

        $wOpt['sign'] = strtoupper(md5($string));

        return $wOpt;
    }


    public static function getAliPay($params)
    {

        $path = Env::get('root_path') . 'public/sdk/alipay';

        require_once($path . '/aop/AopClient.php');
        require_once($path . '/aop/request/AlipayTradeAppPayRequest.php');
        require_once($path . '/aop/SignData.php');


        $aop = new \AopClient();

        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';


        $aop->appId = self::$alipay['appid'];
        $aop->rsaPrivateKey = self::$alipay['rsaPrivateKey'];
        $aop->alipayrsaPublicKey = self::$alipay['alipayrsaPublicKey'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset = 'UTF-8';
        $aop->format = 'json';

        $request = new \AlipayTradeAppPayRequest();

        $notifyUrl = $params['notify_url'];
        $params['type'] = !empty($params['type']) ? $params['type'] : $params['title'];
//        var_dump($params);
        $bizcontent = "{\"body\":\"".$params['type']."\","
            . "\"subject\": \"".$params['title']."\","
            . "\"out_trade_no\": \"".$params['tid']."\","
            . "\"total_amount\": \"".$params['fee']."\","
            . "}";
//        var_dump($bizcontent);
        $request->setNotifyUrl($notifyUrl);

        $request->setBizContent($bizcontent);

        //这里和普通的接口调用不同，使用的是sdkExecute

        $response = $aop->sdkExecute($request);
//        echo htmlspecialchars($response);
        //htmlspecialchars是为了输出到页面时防止被浏览器将关键参数html转义，实际打印到日志以及http传输不会有这个问题
        return $response;
    }


    public static function getAlipayCode($params)
    {

        $path = Env::get('root_path') . 'public/sdk/alipay';

        require_once($path . '/aop/AopClient.php');
        require_once($path . '/aop/request/AlipayTradePrecreateRequest.php');
        require_once($path . '/aop/SignData.php');

        $aop = new \AopClient();

        $aop->gatewayUrl = 'https://openapi.alipay.com/gateway.do';

        $aop->appId = self::$alipay['appid'];
        $aop->rsaPrivateKey = self::$alipay['rsaPrivateKey'];
        $aop->alipayrsaPublicKey = self::$alipay['alipayrsaPublicKey'];
        $aop->apiVersion = '1.0';
        $aop->signType = 'RSA2';
        $aop->postCharset='UTF-8';
        $aop->format='json';


        try{
            $request = new \AlipayTradePrecreateRequest();

            $notifyUrl = $params['notify_url'];

            $request->setNotifyUrl($notifyUrl);

            $request->setBizContent("{" .
                "\"out_trade_no\":\"".$params['tid']."\"," .
                "\"total_amount\":\"".$params['fee']."\"," .
                "\"subject\":\"".$params['title']."\"" .
                "}");

            $result = $aop->execute($request);

            $responseNode = str_replace(".", "_", $request->getApiMethodName()) . "_response";

            $resultCode = $result->$responseNode->code;

            return $result;

        }catch (Exception $e){

            return ($e->getMessage());
        }

        // var_dump($responseNode);
        // var_dump($resultCode);
    }


    public static function array2xml($arr, $level = 1)
    {
        $s = $level == 1 ? "<xml>" : '';
        foreach ($arr as $tagname => $value) {
            if (is_numeric($tagname)) {
                $tagname = $value['TagName'];
                unset($value['TagName']);
            }
            if (!is_array($value)) {
                $s .= "<{$tagname}>" . (!is_numeric($value) ? '<![CDATA[' : '') . $value . (!is_numeric($value) ? ']]>' : '') . "</{$tagname}>";
            } else {
                $s .= "<{$tagname}>" . array2xml($value, $level + 1) . "</{$tagname}>";
            }
        }
        $s = preg_replace("/([\x01-\x08\x0b-\x0c\x0e-\x1f])+/", ' ', $s);
        return $level == 1 ? $s . "</xml>" : $s;
    }


    public static function random($length, $numeric = FALSE)
    {
        $seed = base_convert(md5(microtime() . $_SERVER['DOCUMENT_ROOT']), 16, $numeric ? 10 : 35);
        $seed = $numeric ? (str_replace('0', '', $seed) . '012340567890') : ($seed . 'zZ' . strtoupper($seed));
        if ($numeric) {
            $hash = '';
        } else {
            $hash = chr(rand(1, 26) + rand(0, 1) * 32 + 64);
            $length--;
        }
        $max = strlen($seed) - 1;
        for ($i = 0; $i < $length; $i++) {
            $hash .= $seed{mt_rand(0, $max)};
        }
        return $hash;
    }


    public static function curl($url, $params = false, $ispost = 0, $https = 0)
    {
        $httpInfo = array();
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36');
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        if ($https) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE); // 对认证证书来源的检查
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE); // 从证书中检查SSL加密算法是否存在
        }
        if ($ispost) {
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
            curl_setopt($ch, CURLOPT_URL, $url);
        } else {
            if ($params) {
                if (is_array($params)) {
                    $params = http_build_query($params);
                }
                curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);// 此处就是参数的列表,给你加了个?
            } else {
                curl_setopt($ch, CURLOPT_URL, $url);
            }
        }

        $response = curl_exec($ch);

        if ($response === FALSE) {
            //echo "cURL Error: " . curl_error($ch);
            return false;
        }
        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
        curl_close($ch);
        return $response;
    }
}
